{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "\n",
    "if not any(path.endswith(\"textbook\") for path in sys.path):\n",
    "    sys.path.append(os.path.abspath(\"../../..\"))\n",
    "from textbook_utils import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "np.random.seed(42)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(sec:theory_urn)=\n",
    "\n",
    "# The Urn Model\n",
    "\n",
    "The urn model was developed by Jacob Bernoulli in the early 1700s as a way to model the process of selecting items from a population. The urn model shown in {numref}`Figure %s <sample-urn>` gives a visual description of the process of randomly sampling marbles from an urn. Five marbles were originally in the urn: three black and two white. The diagram shows that two draws were made; first a white marble was drawn and then a black marble. \n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{figure} figures/SampleUrn.png\n",
    "---\n",
    "name: sample-urn\n",
    "---\n",
    "\n",
    "Diagram of two marbles being drawn, without replacement, from an urn\n",
    "```\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To set up an urn model, we first need to make a few decisions:\n",
    "\n",
    "- The number of marbles in the urn\n",
    "- The color (or label) on each marble\n",
    "- The number of marbles to draw from the urn\n",
    "\n",
    "Finally, we also need to decide the sampling process. For our process, we mix the marbles in the urn, and as we select a marble for our sample, we can choose to record the color and return the marble to the urn (with replacement), or set aside the marble so that it cannot be drawn again (without replacement).\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These decisions make up the parameters of our model. We can adapt the urn model to describe many real-world situations by our choice for these parameters. To illustrate, consider the example in {numref}`Figure %s <sample-urn>`. We can _simulate_ the draw of two marbles from our urn without replacement between draws using `numpy`'s `random.choice` method. The `numpy` library supports functions for arrays, which can be particularly useful for data science:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sample 1: ['b' 'w']\n",
      "Sample 2: ['w' 'b']\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "urn = [\"b\", \"b\", \"b\", \"w\", \"w\"]\n",
    "print(\"Sample 1:\", np.random.choice(urn, size=2, replace=False))\n",
    "print(\"Sample 2:\", np.random.choice(urn, size=2, replace=False))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that we set the `replace` argument to `False` to indicate that once we sample a marble, we don't return it to the urn.\n",
    "\n",
    "With this basic setup, we can get approximate answers to questions about the kinds of samples we would expect to see. What is the chance that our sample contains marbles of only one color? Does the chance change if we return each marble after selecting it? What if we changed the number of marbles in the urn? What if we draw more marbles from the urn? What happens if we repeat the process many times?\n",
    "\n",
    "The answers to these questions are fundamental to our understanding of data collection. We can build from these basic skills to simulate the urn and apply simulation techniques to real-world problems that can't be easily solved with classic probability equations.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For example, we can use simulation to easily estimate the fraction of samples where both marbles that we draw match in color. In the following code, we run 10,000 rounds of sampling two marbles from our urn. Using these samples, we can directly compute the proportion of samples with matching marbles:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Proportion of samples with matching marbles: 0.4032\n"
     ]
    }
   ],
   "source": [
    "n = 10_000\n",
    "samples = [np.random.choice(urn, size=2, replace=False) for _ in range(n)]\n",
    "is_matching = [marble1 == marble2 for marble1, marble2 in samples]\n",
    "print(f\"Proportion of samples with matching marbles: {np.mean(is_matching)}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We just carried out a _simulation study_. Our call to `np.random.choice` imitates the chance process of drawing two marbles from the urn without replacement. Each call to `np.random.choice` gives us one possible sample. In a simulation study, we repeat this chance process many times (`10_000` in this case) to get a whole bunch of samples. Then we use the typical behavior of these samples to reason about what we might expect to get from the chance process. While this might seem like a contrived example (it is), consider if we replaced the marbles with people on a dating service, replaced the colors with more complex attributes, and perhaps used a neural network to score a match and you can start to see the foundation of much more sophisticated analysis.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So far we have focused on the sample, but we are often interested in the relationship between the sample we might observe and what it can tell us about the \"population\" of marbles that were originally in the urn.\n",
    "\n",
    "We can draw an analogy to data scope from {numref}`Chapter %s <ch:data_scope>`: a set of marbles drawn from the urn is a _sample_, and the collection of all marbles placed in the urn is the _access frame_, which in this situation we take to be the same as the _population_. This blurring of the difference between the access frame and the population points to the gap between simulation and reality. Simulations tend to simplify models. Nonetheless, they can give helpful insights to real-world phenomena.\n",
    "\n",
    "The urn model, where we do not replace the marbles between draws, is a common selection method called the _simple random sample_. We describe this method and other sampling techniques based on it next.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sampling Designs\n",
    "\n",
    "The process of drawing marbles without replacement from an urn is equivalent to a simple random sample. _In a simple random sample, every sample has the same chance of being selected._\n",
    "While the method name has the word _simple_ in it, constructing a simple random sample is often anything, but simple and in many cases is also the best sampling procedure. Plus, if we are being honest, it can also be a little confusing.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To better understand this sampling method we return to the urn model. Consider an urn with seven marbles. Instead of coloring the marbles, we label each uniquely with a letter `A` through `G`. Since each marble has a different label, we can more clearly identify all possible samples that we might get. Let's select three marbles from the urn without replacement, and use the `itertools` library to generate the list of all combinations:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['ABC', 'ABD', 'ABE', 'ABF', 'ABG', 'ACD', 'ACE', 'ACF', 'ACG', 'ADE', 'ADF', 'ADG', 'AEF', 'AEG', 'AFG', 'BCD', 'BCE', 'BCF', 'BCG', 'BDE', 'BDF', 'BDG', 'BEF', 'BEG', 'BFG', 'CDE', 'CDF', 'CDG', 'CEF', 'CEG', 'CFG', 'DEF', 'DEG', 'DFG', 'EFG']\n",
      "Number of Samples: 35\n"
     ]
    }
   ],
   "source": [
    "from itertools import combinations\n",
    "\n",
    "all_samples = [\"\".join(sample) for sample in combinations(\"ABCDEFG\", 3)]\n",
    "print(all_samples)\n",
    "print(\"Number of Samples:\", len(all_samples))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our list shows that there are 35 unique sets of three marbles. We could have drawn each of these sets six different ways. For example, the set $\\{A, B, C\\}$ can be sampled:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']\n"
     ]
    }
   ],
   "source": [
    "from itertools import permutations\n",
    "\n",
    "print([\"\".join(sample) for sample in permutations(\"ABC\")])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this small example, we can get a complete picture of all the ways in which we can draw any three marbles from the urn.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since each set of three marbles from the population of seven is equally likely to occur, the chance of any one particular sample must be $1/35$:\n",
    "\n",
    "$${\\mathbb{P}}(ABC) = {\\mathbb{P}}(\\textrm{ABD}) = \\cdots = {\\mathbb{P}}(\\textrm{EFG}) = \\frac{1}{35}$$\n",
    "\n",
    "We use the special symbol ${\\mathbb{P}}$ to stand for \"probability\" or \"chance,\" and we read the statement ${\\mathbb{P}}(ABC)$ as \"the chance the sample contains the marbles labeled A, B, and C in any order.\"\n",
    "\n",
    "We can use the enumeration of all of the possible samples from the urn to answer additional questions about this chance process. For example, to find the chance that marble $A$ is in the sample, we can add up the chance of all samples that contain $A$. There are 15 of them, so the chance is:\n",
    "\n",
    "$${\\mathbb{P}}({A~is~in~the~sample}) = \\frac{15}{35} = \\frac{3}{7}$$\n",
    "\n",
    "When it's too difficult to list and count all of the possible samples, we can use simulation to help understand this chance process.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ":::{note}\n",
    "\n",
    "Many people mistakenly think that the defining property of a simple random sample is that every unit has an equal chance of being in the sample. However, this is not the case. A simple random sample of $n$ units from a population of $N$ means that every possible collection of $n$ of the $N$ units has the same chance of being selected. A slight variant of this is the _simple random sample with replacement_, where the units/marbles are returned to the urn after each draw. This method also has the property that every sample of $n$ units from a population of $N$ is equally likely to be selected. The difference, though, is that there are more possible sets of $n$ units because the same marble can appear more than once in the sample.\n",
    "\n",
    ":::\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The simple random sample (and its corresponding urn) is the main building block for more complex survey designs. We briefly describe two of the more widely used designs:\n",
    "\n",
    "Stratified sampling\n",
    ": Divide the population into nonoverlapping groups, called _strata_ (one group is called a _stratum_ and more than one are strata), and then take a simple random sample from each. This is like having a separate urn for each stratum and drawing marbles from each urn, independently. The strata do not have to be the same size, and we need not take the same number of marbles from each.\n",
    "\n",
    "Cluster sampling\n",
    ": Divide the population into nonoverlapping subgroups, called clusters, take a simple random sample of the clusters, and include all of the units in a cluster in the sample. We can think of this as a simple random sample from one urn that contains large marbles that are themselves containers of small marbles. (The large marbles need not have the same number of marbles in them.) When opened, the sample of large marbles turns into the sample of small marbles. (Clusters tend to be smaller than strata.)\n",
    "\n",
    "As an example, we might organize our seven marbles, labeled $A$–$G$, into three clusters, $(A, B)$, $(C,D)$, and $(E, F, G)$. Then, a cluster sample of size one has an equal chance of drawing any of the three clusters. In this scenario, each marble has the same chance of being in the sample:\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "{\\mathbb{P}}({A~\\text{in sample}}) &= {\\mathbb{P}}(\\text{cluster}~{(A,B)~\\text{chosen}}) &= \\frac{1}{3} \\\\\n",
    "{\\mathbb{P}}({B~\\text{in sample}}) &= {\\mathbb{P}}(\\text{cluster}~{(A,B)~\\text{chosen}}) &= \\frac{1}{3} \\\\\n",
    "\\vdots \\\\\n",
    "{\\mathbb{P}}({G~\\text{in sample}}) &= {\\mathbb{P}}(\\text{cluster}~{(E,F,G)~\\text{chosen}}) &= \\frac{1}{3} \\\\\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "But every combination of elements is not equally likely: it is not possible for the sample to include both $A$ and $C$, because they are in different clusters.\n",
    "\n",
    "Often, we are interested in a summary of the sample; in other words, we are interested in a _statistic_. For any sample, we can calculate the statistic, and the urn model helps us find the distribution of possible values that statistic may take on. Next, we examine the distribution of a statistic for our simple example.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sampling Distribution of a Statistic\n",
    "\n",
    "Suppose we are interested in testing the failure pressure of a new fuel tank design for a rocket. It's expensive to carry out the pressure tests since we need to destroy the fuel tank, and we may need to test more than one fuel tank to address variations in manufacturing.\n",
    "\n",
    "We can use the urn model to choose the prototypes to be tested, and we can summarize our test results by the proportion of prototypes that fail the test. The urn model provides us the knowledge that each of the samples has the same chance of being selected, and so the pressure test results are representative of the population.\n",
    "\n",
    "To keep the example simple, let's say we have seven fuel tanks that are labeled like the marbles from before. Let's see what happens when tanks $A$, $B$, $D$, and $F$ fail the pressure test, if chosen, and tanks $C$, $E$, and $G$ pass.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For each sample of three marbles, we can find the proportion of failures according to how many of these four defective prototypes are in the sample. We give a few examples of this calculation:\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Sample     | ABC | BCE | BDF | CEG |\n",
    "| ---------- | --- | --- | --- | --- |\n",
    "| Proportion | 2/3 | 1/3 | 1   | 0   |\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since we are drawing three marbles from the urn, the only possible sample proportions are $0$, $1/3$, $2/3$, and $1$, and for each triple, we can calculate its corresponding proportion. There are four samples that give us all failed tests (a sample proportion of 1). These are $ABD$, $ABF$, $ADF$, and $BDF$, so the chance of observing a sample proportion of 1 is $4/35$. We can summarize the distribution of values for the sample proportion into a table, which we call the _sampling distribution_ of the proportion:\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Proportion of failures | No. of samples | Fraction of samples  |\n",
    "| :-----------------: | :------------: | :------------------: |\n",
    "|          0          |       1        | 1/35 $\\approx 0.03$  |\n",
    "|         1/3         |       12       | 12/35 $\\approx 0.34$ |\n",
    "|         2/3         |       18       | 18/35 $\\approx 0.51$ |\n",
    "|          1          |       4        | 4/35 $\\approx 0.11$  |\n",
    "|        Total        |       35       |          1           |\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While these calculations are relatively straightforward, we can approximate them through a simulation study. To do this, we take samples of three from our population over and over—say 10,000 times. For each sample, we calculate the proportion of failures. That gives us 10,000 simulated sample proportions.\n",
    "The table of the simulated proportions should come close to the sampling distribution. We confirm this with a simulation study.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulating the Sampling Distribution\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Simulation can be a powerful tool to understand complex random processes. In our example of seven fuel tanks, we are able to consider all possible samples from the corresponding urn model. However, in situations with large populations and samples and more complex sampling processes, it may not be tractable to directly compute the chance of certain outcomes. In these situations, we often turn to simulation to provide accurate estimates of the quantities we can't compute directly.\n",
    "\n",
    "Let's set up the problem of finding the sampling distribution of the proportion of failures in a simple random sample of three fuel tanks as an urn model. Since we are interested in whether or not the tank fails, we use 1 to indicate a failure and 0 to indicate a pass, giving us an urn with marbles labeled as follows:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "urn = [1, 1, 0, 1, 0, 1, 0]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We have encoded the tanks $A$ through $G$ using 1 for fail and 0 for pass, so we can take the `mean` of the sample to get the proportion of failures in a sample:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sample: [1 0 0]\n",
      "Prop Failures: 0.3333333333333333\n"
     ]
    }
   ],
   "source": [
    "sample = np.random.choice(urn, size=3, replace=False)\n",
    "print(f\"Sample: {sample}\")\n",
    "print(f\"Prop Failures: {sample.mean()}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In a simulation study, we repeat the sampling process thousands of times to get thousands of proportions, and then we estimate the sampling distribution of the proportion from what we get in our simulation. Here, we construct 10,000 samples (and so 10,000 proportions):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "samples = [np.random.choice(urn, size=3, replace=False) for _ in range(10_000)]\n",
    "prop_failures = [s.mean() for s in samples]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can study these 10,000 sample proportions and match our findings against what we calculated already using the complete enumeration of all 35 possible samples. We expect the simulation results to be close to our earlier calculations because we have repeated the sampling process many, many times. That is, we want to compare the fraction of the 10,000-sample proportion that is 0, $1/3$, $2/3$, and 1 to those we computed exactly; those fractions are $1/35$, $12/35$, $18/35$, and $4/35$, or about $0.03$, $0.34$, $0.51$, and $0.11$:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Proportion of Failures</th>\n",
       "      <th>Fraction of Samples</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.00</td>\n",
       "      <td>0.03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.33</td>\n",
       "      <td>0.35</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.67</td>\n",
       "      <td>0.51</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1.00</td>\n",
       "      <td>0.11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Proportion of Failures  Fraction of Samples\n",
       "0                    0.00                 0.03\n",
       "1                    0.33                 0.35\n",
       "2                    0.67                 0.51\n",
       "3                    1.00                 0.11"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unique_els, counts_els = np.unique(prop_failures, return_counts=True)\n",
    "pd.DataFrame({\n",
    "    \"Proportion of failures\": unique_els,\n",
    "    \"Fraction of samples\": counts_els / 10_000,\n",
    "})"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The simulation results closely match the exact chances that we calculated earlier.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ":::{note}\n",
    "\n",
    "Simulation studies leverage random number generators to sample many outcomes from a random process. In a sense, simulation studies convert complex random processes into data that we can readily analyze using the broad set of computational tools we cover in this book. While simulation studies typically do not provide definitive proof of a particular hypothesis, they can provide important evidence. In many situations, simulation is the most accurate estimation process we have.\n",
    "\n",
    ":::\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Drawing marbles from an urn with 0s and 1s is such a popular framework for understanding randomness that this chance process has been given a formal name, _hypergeometric distribution_, and most software provides functionality to rapidly carry out simulations of this process. In the next section, we simulate the hypergeometric distribution of the fuel tank example.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation with the Hypergeometric Distribution\n",
    "\n",
    "Instead of using `random.choice`, we can use `numpy`'s `random.hypergeometric` to simulate drawing marbles from the urn and counting the number of failures. The `random.hypergeometric` method is optimized for the 0-1 urn and allows us to ask for 10,000 simulations in one call. For completeness, we repeat our simulation study and calculate the empirical proportions:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 1 2 ... 1 2 2]\n"
     ]
    }
   ],
   "source": [
    "simulations_fast = np.random.hypergeometric(\n",
    "    ngood=4, nbad=3, nsample=3, size=10_000\n",
    ")\n",
    "print(simulations_fast)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(We don't think that a pass is \"bad\"; it's just a naming convention to call the type you want to count \"good\" and the other \"bad\".)\n",
    "\n",
    "We tally the fraction of the 10,000 samples with 0, 1, 2, or 3 failures:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Number of Failures</th>\n",
       "      <th>Fraction of Samples</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>0.03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>0.34</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2</td>\n",
       "      <td>0.52</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3</td>\n",
       "      <td>0.11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Number of Failures  Fraction of Samples\n",
       "0                   0                 0.03\n",
       "1                   1                 0.34\n",
       "2                   2                 0.52\n",
       "3                   3                 0.11"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unique_els, counts_els = np.unique(simulations_fast, return_counts=True)\n",
    "pd.DataFrame({\n",
    "    \"Number of failures\": unique_els,\n",
    "    \"Fraction of samples\": counts_els / 10_000,\n",
    "})"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You might have asked yourself already: since the hypergeometric is so popular, why not provide the exact distribution of the possible values? In fact, we can calculate these exactly:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Number of Failures</th>\n",
       "      <th>Fraction of Samples</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>0.03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>0.34</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2</td>\n",
       "      <td>0.51</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3</td>\n",
       "      <td>0.11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Number of Failures  Fraction of Samples\n",
       "0                   0                 0.03\n",
       "1                   1                 0.34\n",
       "2                   2                 0.51\n",
       "3                   3                 0.11"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from scipy.stats import hypergeom\n",
    "\n",
    "num_failures = [0, 1, 2, 3]\n",
    "pd.DataFrame({\n",
    "    \"Number of failures\": num_failures,\n",
    "    \"Fraction of samples\": hypergeom.pmf(num_failures, 7, 4, 3),\n",
    "})"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ":::{note}\n",
    "\n",
    "Whenever possible, it's a good idea to use the functionality provided in a third-party package for simulating from a named distribution, such as the random number generators offered in `numpy`, rather than writing your own function. It's best to take advantage of efficient and accurate code that others have developed. That said, building from scratch on occasion can help you gain an understanding of an algorithm, so we recommend trying it.\n",
    "\n",
    ":::\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Perhaps the two most common chance processes are those that arise from counting the number of 1s drawn from a 0-1 urn: drawing without replacement is the _hypergeometric_ distribution and drawing with replacement is the _binomial_ distribution.\n",
    "\n",
    "While this simulation was so simple that we could have used `hypergeom.pmf` to directly compute our distribution, we wanted to demonstrate the intuition that a simulation study can reveal. The approach we take in this book is to develop an understanding of chance processes based on simulation studies. However, we do formalize the notion of a probability distribution of a statistic (like the proportion of fails in a sample) in\n",
    "{numref}`Chapter %s <ch:inf_pred_theory>`.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have simulation as a tool for understanding accuracy, we can revisit the election example from {numref}`Chapter %s <ch:data_scope>` and carry out a post-election study of what might have gone wrong with the voter polls. This simulation study imitates drawing more than a thousand marbles (voters who participate in the poll) from an urn of six million. We can examine potential sources of bias and the variation in the polling results, and we can carry out a what-if analysis where we examine how the predictions might have gone if a larger number of draws from the urn were taken.\n"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
